package gdr.connection;

import gdr.battle.core.online.ServerManager;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;

/**
 * Gestisce la comunicazione con un client
 * @author Giorgio Vitale
 *
 */
public class ServerThread implements Runnable{
	protected UserData datiUtente;
	
	//variabili per la gestione del canale
	protected Socket socket;
	protected ObjectInputStream ois;
	protected ObjectOutputStream oos;
	protected boolean stop;
	protected Thread serverThread;
	protected ServerManager manager;
	
	
	public ServerThread(ServerManager manager, Socket s, ObjectInputStream inputStream, ObjectOutputStream outputStream){
		this.manager = manager;
		socket = s;
		ois = inputStream;
		oos = outputStream;
		stop = false;
		datiUtente = new UserData();
	}
	
	public void start(){
		if (serverThread!=null) return;
		serverThread = new Thread(this);
		serverThread.start();
	}

	public void stopServerThread(){
		if (stop) return;
		stop = true;
		try{
			ois.close();
			oos.close();
			socket.close();
			manager.removeConnection(this);
		} catch (Exception e) { oos=null; ois=null; socket=null;}
	}
	
	public void run(){
		while (!stop){
			try{
				Object o = ois.readObject();
				manager.elaboraRichiesta(this, o);
			}catch (Exception e)
			{	stopServerThread();
			}
		}
	}
	
	public void sendMessage(Object o){
		try{
			oos.writeObject(o);
		} catch(Exception e)
		{	stopServerThread();
		}
	}

	public UserData getDatiUtente() {
		return datiUtente;
	}

	public void setDatiUtente(UserData datiUtente) {
		this.datiUtente = datiUtente;
	}

	@Override
	public String toString() {
		return "ServerThread [datiUtente=" + datiUtente + ", stop=" + stop
				+ "]";
	}

	
}